package com.weimin.ghostdrop.service.impl;

import com.weimin.ghostdrop.service.FileStorageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

/**
 * @author : huiMing
 * Date : 2025年07月31日 14:16
 * @version V1.0
 */

@Service
public class FileStorageServiceImpl implements FileStorageService {

    @Value("${file.base-url}")
    private String baseUrl;

    private final Path fileStorageLocation;

    // 构造函数，初始化文件存储目录
    public FileStorageServiceImpl(@Value("${file.upload-dir}") String uploadDir) {
        this.fileStorageLocation = Paths.get(uploadDir).toAbsolutePath().normalize();
        try {
            Files.createDirectories(this.fileStorageLocation); // 创建目录如果不存在
        } catch (Exception ex) {
            throw new RuntimeException("Could not create the directory where the uploaded files will be stored.", ex);
        }
    }

    @Override
    public String storeFile(MultipartFile file) throws IOException {
        String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());
        String fileExtension = "";
        int dotIndex = originalFilename.lastIndexOf('.');
        if (dotIndex > 0 && dotIndex < originalFilename.length() - 1) {
            fileExtension = originalFilename.substring(dotIndex);
        }

        // 生成唯一文件名
        String fileName = UUID.randomUUID().toString() + fileExtension;
        Path targetLocation = this.fileStorageLocation.resolve(fileName);
        Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

        // 返回文件在服务器上的相对路径 (例如: /images/unique_filename.jpg)
//        return baseUrl + fileName;
        return fileName;
    }

    @Override
    public String getFileUrl(String relativePath) {
        // 如果relativePath已经是完整的URL，则直接返回
        if (relativePath.startsWith("http://") || relativePath.startsWith("https://") || relativePath.startsWith(baseUrl)) {
            return relativePath;
        }
        return baseUrl + relativePath;
    }

    @Override
    public Path load(String filename) {
        return fileStorageLocation.resolve(filename);
    }

}
